package com.alibaba.wallet.service;

import com.alibaba.api.pojos.Account;
import com.alibaba.api.pojos.Trade;
import com.alibaba.api.service.AccountServiceApi;
import com.alibaba.wallet.mapper.AccountMapper;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;

@Service(version = "1.0.0")
public class AccountServiceImpl implements AccountServiceApi {

    @Autowired
    private AccountMapper accountMapper;

    @Override
    public boolean accountByMoney(Long id,Double money, Integer type) {
        double num = 0;
        Account account = findById(id);
        if (account == null) {
            return false;
        }
        if (type == 1) {
            //充值
            num = account.getBalance() + money;
        }else {
            //提取
            num = account.getBalance() - money;
            if (num < 0) {
                return false;
            }
        }
        account.setBalance(num);
        accountMapper.updateById(account);
        //记录交易信息
        try {
            Trade trade = new Trade();
            trade.setAccountId(account.getAccountId());
            trade.setTradeMone(num);
            trade.setTradeType(type);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }

    @Override
    public Account findById(Long id) {
        Account account = accountMapper.selectById(id);
        return account;
    }

    @Override
    public boolean insert(Account account) {
        return accountMapper.insert(account) == 1;
    }
}
